<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2016/10/29
 * Time: 16:56
 */

namespace J;


use J\Web\Session;

/**
 * 当前登录用户信息
 *
 * @property string name      用户名
 * @property string nickname  昵称
 * @property int    id
 *
 * @property array  authorize   权限数组
 * @property array  roles       角色数组
 * @property array  departments 部门数组
 *
 *
 */
class User extends Util\User
{
    /**
     * @var \Closure
     */
    protected $door;

    public function __construct(\Closure $door)
    {
        $this->door = $door;
        if (!empty(Session::get(self::USER_SESSION_KEY)))
            $this->login(Session::get(self::USER_SESSION_KEY));
    }

    public function logout()
    {
        Session::del(self::USER_SESSION_KEY);
        parent::logout();
    }

    public function login(array $attributes)
    {
        parent::login($attributes);
        Session::set(self::USER_SESSION_KEY, $attributes);
    }

    protected function fill($key, $value)
    {
        parent::fill($key, $value);
        Session::set(self::USER_SESSION_KEY, $this->attributes);
    }

    public function getLoginMiddleware(\Closure $next)
    {
        return function (Intent $intent) use ($next){
            $intent->getApp()->debug(Message::AUTH_LOGIN_BEGIN);

            // 登陆验证
            if (!$this->isLogin() ) {
                $intent->getContext()->getUrl()->push();
                return $intent->jump('Login');
            }

            if (strtolower($intent->controller) === 'install') {
                if (!$this->isAdministrator()) return false;
            }

            $intent->getApp()->debug(Message::AUTH_LOGIN_END);
            return $next($intent);
        };
    }

    public function getAdminMiddleware(\Closure $next)
    {
        return function (Intent $intent) use ($next){
            $intent->getApp()->debug(Message::AUTHORIZATION_BEGIN);

            if (!$this->authorized($intent->createAuthorityString())) {
                throw new Exception(Message::AUTH_FORBID);
            }

            $intent->getApp()->debug(Message::AUTHORIZATION_END);
            return $next($intent);
        };
    }

    protected function getMyInformation($information)
    {
        return ($this->door)($information, $this);
    }
}